package com.jyxd.web.hiscz.service;

import com.jyxd.web.data.dictionary.*;
import com.jyxd.web.data.user.User;
import com.jyxd.web.error.JyxdException;
import com.jyxd.web.hiscz.dto.DictionariesDTO;
import com.jyxd.web.hiscz.dto.DictionariesResponse;
import com.jyxd.web.service.dictionary.*;
import com.jyxd.web.service.user.RoleService;
import com.jyxd.web.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

import static com.jyxd.web.hiscz.service.HisUtilService.*;
import static com.jyxd.web.util.ExecuteUtil.errorIfEmpty;
import static com.jyxd.web.util.ObjectUtil.castList;
import static com.jyxd.web.util.UUIDUtil.getUUID;

@Service
public class HisDictionaryService {


    private static Logger logger = LoggerFactory.getLogger(HisDictionaryService.class);

    private static  List<Map<String, Object>> nurseList =new ArrayList<Map<String, Object>>();//护士信息

    @Autowired
    private DepartmentDictionaryService departmentDictionaryService;
    @Autowired
    private WardDictionaryService wardDictionaryService;
    @Autowired
    private BedDictionaryService bedDictionaryService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DuryDictionaryService duryDictionaryService;
    @Autowired
    private JobDictionaryService jobDictionaryService;
    @Autowired
    private TitleDictionaryService titleDictionaryService;
    @Autowired
    private CommentItemService commentItemService;


    public DictionariesResponse requestDictionary(DictionariesDTO dictionaries) {
        String type = null;
        try {
            errorIfEmpty(dictionaries, "请求参数不能为空");

            errorIfEmpty(dictionaries.getDictInfo(), "请求参数不能为空");

            logger.info("DictInfo >> " + dictionaries.getDictInfo());

            type = dictionaries.getDictInfo().getDictCode();

            logger.info("type >> 值为 ： " + type);
            List<Object> entityList = castList(dictionaries.getDictInfo().getRecordInfo(), Object.class);
            if (CollectionUtils.isEmpty(entityList)) {
                throw new JyxdException("主数据list不能为空");
            }
            for (Object entity : entityList) {
                Map<String, Object> entityMap = (Map<String, Object>) entity;
                switch (type) {
                    case "DictDept": // 科室字典
                        setDictDept(entityMap);
                        break;
                    case "DictDomain": //病区字典
                        setDictDomain(entityMap);
                        break;
                    case "DictBed": // 床位字典
                        setDicBed(entityMap);
                        break;
                    case "DictStaff"://人员字典
                        setDictStaff(entityMap);
                        break;
                    case "DictTitle": // 职称主数据
                        setTitle(entityMap);
                        break;
                    case "DictJob": // 岗位角色主数据
                        setJob(entityMap);
                        break;
                    case "DictDuty": // 职务主数据
                        setDuty(entityMap);
                        break;
                    case "DictMedicineWay": // 给药途径主数据
                        setMedicineWay(entityMap);
                        break;
                    default:
                        throw new JyxdException("需要字典code不正确");
                }
            }
            return new DictionariesResponse("1", "字典信息接收成功", null);
        } catch (Exception e) {
            logger.info(type + "字典信息接收错误：" + e.getMessage());
            return new DictionariesResponse("0", e.getMessage(), null);
        }
    }

    /**
     * 给药途径字典
     *
     * @param objectMap
     * @return
     */
    private boolean setMedicineWay(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cMedicineWayCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "给药途径编码不存在");
        Map<String, Object> map = new HashMap<>();
        map.put("commonItemName", code);
        map.put("type", "use_mode");
        CommenItemDictionary itemDictionary = commentItemService.queryDataNameAndType(map);
        if (Objects.isNull(itemDictionary)) {
            itemDictionary = new CommenItemDictionary();
            itemDictionary.setId(getUUID());
            itemDictionary.setStatus(1);
            dicFlag = true;
        }
        itemDictionary.setCommonItemName(code);
        itemDictionary.setType("use_mode");
        itemDictionary.setDescription(getIsNullObject(objectMap, "cMedicineWayName", String.class, EXCEPTION_TYPE_STRING)); // 给药途径描述
        return dicFlag ? commentItemService.insert(itemDictionary) : commentItemService.update(itemDictionary);
    }

    /**
     * 职称字典
     *
     * @param objectMap
     * @return
     */
    private boolean setTitle(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cTitleCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "职称编码不存在");
        TitleDictionary titleDictionary = titleDictionaryService.queryDataByCode(code);
        if (Objects.isNull(titleDictionary)) {
            titleDictionary = new TitleDictionary();
            titleDictionary.setId(getUUID());
            titleDictionary.setStatus(1);
            dicFlag = true;
        }
        titleDictionary.setTitleCode(code);
        titleDictionary.setTitleName(getIsNullObject(objectMap, "cTitleName", String.class, EXCEPTION_TYPE_STRING));
        return dicFlag ? titleDictionaryService.insert(titleDictionary) : titleDictionaryService.update(titleDictionary);
    }

    /**
     * 岗位角色字典
     *
     * @param objectMap
     * @return
     */
    private boolean setJob(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cJobCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "岗位角色编码不存在");
        JobDictionary jobDictionary = jobDictionaryService.queryDataByCode(code);
        if (Objects.isNull(jobDictionary)) {
            jobDictionary = new JobDictionary();
            jobDictionary.setId(getUUID());
            jobDictionary.setStatus(1);
            dicFlag = true;
        }
        jobDictionary.setJobCode(code);
        jobDictionary.setJobName(getIsNullObject(objectMap, "cJobName", String.class, EXCEPTION_TYPE_STRING));
        return dicFlag ? jobDictionaryService.insert(jobDictionary) : jobDictionaryService.update(jobDictionary);
    }

    /**
     * 职务字典
     *
     * @param objectMap
     * @return
     */
    private boolean setDuty(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cDutyCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "职务编码不存在");
        DutyDictionary dutyDictionary = duryDictionaryService.queryDataByCode(code);
        if (Objects.isNull(dutyDictionary)) {
            dutyDictionary = new DutyDictionary();
            dutyDictionary.setId(getUUID());
            dutyDictionary.setStatus(1);
            dicFlag = true;
        }
        dutyDictionary.setDutyCode(code);
        dutyDictionary.setDutyName(getIsNullObject(objectMap, "cDutyName", String.class, EXCEPTION_TYPE_STRING));
        return dicFlag ? duryDictionaryService.insert(dutyDictionary) : duryDictionaryService.update(dutyDictionary);
    }

    /**
     * 科室字典
     *
     * @param objectMap
     */
    private boolean setDictDept(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cDeptCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "科室编码不存在");
        Map<String, Object> map = new HashMap<>();
        map.put("departmentCode", code);
        DepartmentDictionary departmentDictionary = departmentDictionaryService.queryDataByCode(map);
        if (Objects.isNull(departmentDictionary)) {
            departmentDictionary = new DepartmentDictionary();
            departmentDictionary.setId(getUUID());
            departmentDictionary.setStatus(1);
            dicFlag = true;
        }
        departmentDictionary.setDepartmentCode(code); // 获取科室编码
        departmentDictionary.setDepartmentName(getIsNullObject(objectMap, "cDeptName", String.class, EXCEPTION_TYPE_STRING)); // 获取科室名称
        departmentDictionary.setDomainId(getIsNullObject(objectMap, "cDomainid", String.class, EXCEPTION_TYPE_STRING));
        departmentDictionary.setStatus(getIsNullObject(objectMap, "bUseFlag", Integer.class, EXCEPTION_TYPE_INTEGER)); // 启用状态
        if (Objects.isNull(departmentDictionary.getStatus())) {
            departmentDictionary.setStatus(1);
        }
        return dicFlag ? departmentDictionaryService.insert(departmentDictionary) : departmentDictionaryService.update(departmentDictionary);
    }


    /**
     * 病区字典
     *
     * @param objectMap
     */
    private boolean setDictDomain(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String code = getIsNullObject(objectMap, "cStandCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(code, "病区编码不存在");
        WardDictionary wardDictionary = wardDictionaryService.queryDataByCode(code);
        if (Objects.isNull(wardDictionary)) {
            wardDictionary = new WardDictionary();
            wardDictionary.setId(getUUID());
            wardDictionary.setStatus(1);
            dicFlag = true;
        }
        wardDictionary.setWardCode(code);
        wardDictionary.setWardName(getIsNullObject(objectMap, "cDomainName", String.class, EXCEPTION_TYPE_STRING));
        wardDictionary.setStatus(getIsNullObject(objectMap, "bUseFlag", Integer.class, EXCEPTION_TYPE_INTEGER)); // 启用状态
        return dicFlag ? wardDictionaryService.insert(wardDictionary) : wardDictionaryService.update(wardDictionary);
    }


    /**
     * 床位字典
     *
     * @param objectMap
     */
    private boolean setDicBed(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String iBed = getIsNullObject(objectMap, "iBed", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(iBed, "床位id不存在");
        BedDictionary bedDictionary = bedDictionaryService.queryDataByAppCode(iBed);
        if (Objects.isNull(bedDictionary)) {
            bedDictionary = new BedDictionary();
            bedDictionary.setId(getUUID());
            bedDictionary.setStatus(1);
            dicFlag = true;
        }
        String cBedCode = getIsNullObject(objectMap, "cBedCode", String.class, EXCEPTION_TYPE_STRING); // 获取床位号
        String iRoom = getIsNullObject(objectMap, "iRoom", String.class, EXCEPTION_TYPE_STRING); // 获取病房号
        String iClinicDept = getIsNullObject(objectMap, "iClinicDept", String.class, EXCEPTION_TYPE_STRING); // 获取科室编码
        bedDictionary.setBedName(cBedCode);
        String[] split = cBedCode.split("-");
        if (Objects.nonNull(split) && split.length > 1){
            bedDictionary.setBedCode(split[1]);
        }
        bedDictionary.setRoomCode(iRoom);
        bedDictionary.setOfficeCode(iClinicDept);
        bedDictionary.setAppCode(iBed);
        return dicFlag ? bedDictionaryService.insert(bedDictionary) : bedDictionaryService.update(bedDictionary);
    }

    /**
     * 人员字典
     *
     * @param objectMap
     */
    private boolean setDictStaff(Map<String, Object> objectMap) {
        boolean dicFlag = false;
        String workNumber = getIsNullObject(objectMap, "StaffCode", String.class, EXCEPTION_TYPE_STRING);
        errorIfEmpty(workNumber, "人员工号不存在");
        User user = userService.queryDataByCode(workNumber);
        if (Objects.isNull(user)) {
            user = new User();
            user.setId(getUUID());
            user.setStatus(1);//状态
            dicFlag = true;
        }
        user.setAppId(getIsNullObject(objectMap, " iStaff", String.class, EXCEPTION_TYPE_STRING)); // 用户第三方id
        user.setWorkNumber(getIsNullObject(objectMap, "StaffCode", String.class, EXCEPTION_TYPE_STRING));//工号
        user.setLoginName(getIsNullObject(objectMap, "StaffCode", String.class, EXCEPTION_TYPE_STRING));//账号
        user.setPassword("e10adc3949ba59abbe56e057f20f883e");//默认密码123456
        user.setUserName(getIsNullObject(objectMap, "StaffName", String.class, EXCEPTION_TYPE_STRING));//姓名
        user.setSimplicity(getIsNullObject(objectMap, "PyCode", String.class, EXCEPTION_TYPE_STRING));//拼音简拼
        Integer noSex = getIsNullObject(objectMap, "No_Sex", Integer.class, EXCEPTION_TYPE_INTEGER);
        user.setSex(Objects.isNull(noSex) ? 0 : noSex);//性别
        user.setUserTypeCode(getIsNullObject(objectMap, "iStaffType", String.class, EXCEPTION_TYPE_STRING));//类型编码
       /* Map<String, Object> map = new HashMap<>();
        map.put("userTypeCode", getIsNullObject(objectMap, "iStaffType", String.class, EXCEPTION_TYPE_STRING));
        Role role = roleService.queryDataByTypeCode(map);
        if (Objects.isNull(role)) {
            user.setRoleId(role.getId());//角色id
        }*/
        user.setRoleId("00");//角色id

        user.setEnterTime(getTime(objectMap.get("dWorkDate")));//工作时间
        user.setCreateTime(new Date());//创建时间
        user.setDeptCode(getIsNullObject(objectMap, "NO_Dept", String.class, EXCEPTION_TYPE_STRING));//所属科室
        return dicFlag ? userService.insert(user) : userService.update(user);
    }

    public List<Map<String, Object>> getNurseList(){
        return nurseList;
    }

    public void setNurseList( List<Map<String, Object>> newNurseList){
        nurseList = newNurseList;
    }




}
